﻿using GuardMonitor.Model;
using GuardMonitor.Utils;
using Newtonsoft.Json.Linq;
using SmartWeighMonitor;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using 新门禁.Utils;
using 门禁系统.ViewModel;

namespace 新门禁
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        MainViewModel mainViewModel;
        MainWindow mainWindow;
        private DispatcherTimer timer;

        System.Windows.Forms.PictureBox m_pictureBox01;
        System.Windows.Forms.PictureBox m_pictureBox02;
        
        SynchronizationContext _syncContext = null;
        private DispatcherTimer timerReadIDCard;

        delegate void MyDelegate(Object value);
        private VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK m_PlateResultCB = null;
        private VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK m_PlateResultCB2 = null;
        private VzClientSDK.VZLPRC_GPIO_RECV_CALLBACK m_gpio_recvCB = null;

        private string m_sAppPath;

        public MainWindow()
        {
            InitializeComponent();
           // TcpRequestUtil.Main("in");
            _syncContext = SynchronizationContext.Current;
            m_sAppPath = System.IO.Directory.GetCurrentDirectory();
            mainViewModel = new MainViewModel();
            this.DataContext = mainViewModel;

            m_pictureBox01 = new System.Windows.Forms.PictureBox();
            m_pictureBox02 = new System.Windows.Forms.PictureBox();
            videoHost01.Child = m_pictureBox01;
            videoHost02.Child = m_pictureBox02;

            mainWindow = this;
            this.Loaded += Window_Loaded;
            this.Unloaded += Window_UnLoad;
            int seconds = App.GetBaseInfo().RefreshSeconds;
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(seconds);
            timer.Tick += new EventHandler(timeCycle);
            timer.Start();

            string Time = App.GetBaseInfo().IdReadCardTime;//读取身份证物理卡号定时任务
            int IdReadCardTime = int.Parse(Time); 
            timerReadIDCard = new DispatcherTimer();
            timerReadIDCard.Interval = TimeSpan.FromSeconds(IdReadCardTime);
            timerReadIDCard.Tick += new EventHandler(timeReadIdCard);
            timerReadIDCard.Start();
        }



        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            version.Text = "门禁系统 ver.1.0.1";
            VzClientSDK.VzLPRClient_Setup();
            m_gpio_recvCB = new VzClientSDK.VZLPRC_GPIO_RECV_CALLBACK(OnGPIORecv);

            HttpServer server = App.GetHttpServer();
            if (null != server)
            {
                HttpServer.sendMsgEvent += Server_sendMsgEvent;
            }

            int code = NewIDcardread.Opendevice();//打开读卡设备
            if (code != 1)
            {

                MessageBox.Show("打开设备失败");

            }

            LoadData();

        }
        private void Window_UnLoad(object sender, EventArgs e)
        {
            string sMsg = string.Empty;

                try
                {

                    int ret = NewIDcardread.closeID();//关闭读卡器
                    if (ret != 1)
                    {
                        return;
                    }
                }
                catch { }
            
            
        }

        public async void timeReadIdCard(object sender, EventArgs e)
        {

            timerReadIDCard.Stop(); // 立即停止定时器防止重叠调用
            /*  MyDelegate d = new MyDelegate(doReadIdCard);
              this.Dispatcher.Invoke(d, "");*/
            // 后台执行阻塞操作
            await Task.Run(() =>
            {

                StringBuilder driverMacCard = new StringBuilder(16);
                int code = NewIDcardread.ReadIINSNDN(driverMacCard);
                if (code == 1)
                {
                    string facId = driverMacCard.ToString();
                    Application.Current.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        carApproachbyguid(facId);//juid请求接口获取车号
                    }));
                }
            });
            // 重启定时器（无需等待后台任务完成）
            timerReadIDCard.Start();
        }
  

        private void carApproachbyguid(String guid)
        {
            String gateCode = App.GetBaseInfo().gateCode;
            String ip = App.GetBaseInfo().HttpServerIp;
            String port = App.GetBaseInfo().HttpServerPort;

            JObject paramjson = new JObject();
            paramjson.Add("guid", guid.ToString());
            paramjson.Add("gateCode", App.GetBaseInfo().gateCode);
            String result = HttpPostHelper.doHttpPost("http://" + ip + ":" + port + "/ytBill/carApproachbyguid", paramjson.ToString());
            JObject resJSON = JObject.Parse(result);
            string status = (string)resJSON.GetValue("status");
            string message = (string)resJSON.GetValue("msg");
            string carNum = (string)resJSON.GetValue("carNo");
            string type = (string)resJSON.GetValue("type");


            if ("success".Equals(status))
            {
                if ("in".Equals(type))
                {
                    txtInCarNo.Text = carNum;
                    txtInResult.Foreground = Brushes.Green;
                    txtInResult.Text = "正常放行";
                }
                else if ("out".Equals(type))
                {
                    txtOutCarNo.Text = carNum;
                    txtOutResult.Foreground = Brushes.Green;
                    txtOutResult.Text = "正常放行";
                }
                String comm = App.GetBaseInfo().IO_Com_PortName;
            }
            else
            {
                if ("in".Equals(type))
                {
                    txtInResult.Foreground = Brushes.Red;
                    txtInResult.Text = message;

                }
                else if ("out".Equals(type))
                {
                    txtOutResult.Foreground = Brushes.Red;
                    txtOutResult.Text = message;

                }
            }

        }
        private void OnGPIORecv(int handle, int nGPIOId, int nVal, IntPtr pUserData)
        {
            int value = nVal;
        }



        private void LoadData()
        {
            //new Task(() =>
            //{
            //    Invoke();
            //}).Start();

            new Task(() =>
            {
                getAccessList();
            }).Start();
        }
        private async void getAccessList()
        {
            try
            {
                String gateCode = App.GetBaseInfo().gateCode;
                String[] gatecodes = gateCode.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                String ip = App.GetBaseInfo().HttpServerIp;
                String port = App.GetBaseInfo().HttpServerPort;
                //String port = App.GetBaseInfo().AuthHttpServerPort;
                JArray jArray = new JArray();
                for (int i = 0; i < gatecodes.Length; i++)
                {
                    JObject json = new JObject();
                    //json.Add("gateCode", gatecodes[i]);
                    json.Add("id", gatecodes[i]);
                    jArray.Add(json);
                }
                //String bodyJsonStr = "{\"gateCode\":\"" + gateCode + "\"}";
                JObject newJson = new JObject();
                newJson.Add("jsonList", jArray);
                var result = HttpPostHelper.doHttpAsyncPost("http://" + ip + ":" + port + "/qd-s-factory/accessLists", newJson.ToString());
                //var result = HttpPostHelper.doHttpAsyncPost("http://" + ip + ":" + port + "/qd-s-factory/access/accessList", newJson.ToString());
                String msg = await result;
                JObject respJson = JObject.Parse(msg);
                String status = respJson["success"].ToString();
                if ("true".Equals(status.ToLower()))
                {
                    _syncContext.Post(SetDataLists, respJson);

                }
            }
            catch (Exception ex)
            {
                LogObject.WriteLog(ex.ToString(), "Message");

            }
        }

        private void SetDataLists(object obj)
        {
            string flag = App.GetBaseInfo().ButtonLimit;
            try
            {

                JObject jsonObj = obj as JObject;
                bool success = (bool)jsonObj.GetValue("success");
                if (!success) return;
                int idx = 0;
                mainViewModel.carInList.Clear();
                JObject dataObj = (JObject)jsonObj.GetValue("data");
                JArray waitInArray = (JArray)dataObj.GetValue("willInList");
                String check = (String)jsonObj.GetValue("check");


                idx = 0;
                foreach (JObject item in waitInArray)
                {
                    idx++;
                    Record record = getRecordByJSON(item);
                    record.xh = idx.ToString();
                    if (flag.Equals("1"))
                    {
                        record.Visibility = "Visible";
                    }
                    else
                    {
                        record.Visibility = "Hidden";
                    }

                    if (flag.Equals("1"))
                    {
                        record.checkVisibility = "Visible";
                    }
                    else
                    {
                        record.checkVisibility = "Hidden";

                    }
                    mainViewModel.carInList.Add(record);
                }

                mainViewModel.carInList2.Clear();
                idx = 0;
                JArray hasInArray = (JArray)dataObj.GetValue("inList");
                foreach (JObject item in hasInArray)
                {
                    idx++;
                    Record record = getRecordByJSON(item);
                    record.xh = idx.ToString();
                    mainViewModel.carInList2.Add(record);
                }

                mainViewModel.carOutList.Clear();
                idx = 0;
                JArray waitOutArray = (JArray)dataObj.GetValue("willOutList");
                foreach (JObject item in waitOutArray)
                {
                    idx++;
                    Record record = getRecordByJSON(item);
                    record.xh = idx.ToString();
                    if (flag.Equals("1"))
                    {
                        record.Visibility = "Visible";
                    }
                    else
                    {
                        record.Visibility = "Hidden";
                    }
                    mainViewModel.carOutList.Add(record);
                }

                mainViewModel.carOutList2.Clear();
                idx = 0;
                JArray hasOutArray = (JArray)dataObj.GetValue("outList");
                foreach (JObject item in hasOutArray)
                {
                    idx++;
                    Record record = getRecordByJSON(item);
                    record.xh = idx.ToString();
                    mainViewModel.carOutList2.Add(record);
                }
            }
            catch (Exception ex)
            {
                LogObject.WriteLog("send message: ", "loadData");

            }
        }
        public Record getRecordByJSON(JObject item)
        {
            Record record = new Record();
            record.id = (String)item.GetValue("id");
            record.xh = (String)item.GetValue("xh");
            record.carNo = (String)item.GetValue("carNo");
            record.invName = (String)item.GetValue("invName");
            record.orderNo = (String)item.GetValue("orderNo");
            record.cTime = (String)item.GetValue("cTime");

            String status = (String)item.GetValue("checkStatus");
            if (status.Equals("0"))
            {
                record.CheckStatus = "待安检";
            }
            else if (status.Equals("1"))
            {
                record.CheckStatus = "安检通过";
            }
            else
            {
                record.CheckStatus = "安检未通过";
            }



            return record;
        }

     
        private void DGInList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }

        private void Server_sendMsgEvent(object msg)
        {
            MyDelegate dele = new MyDelegate(DealMessage);
            this.Dispatcher.Invoke(dele, msg);
        }

        void DealMessage(object obj)
        {
            JObject jsonObj = JObject.Parse(obj.ToString());
            String type = (String)jsonObj.GetValue("type");
            if ("GetCarNo".Equals(type))
            {
                JObject jsonDetail = (JObject)jsonObj.GetValue("detail");
                String inOut = (String)jsonDetail.GetValue("inOut");
                String carNo = (String)jsonDetail.GetValue("carNo");
                if ("in".Equals(inOut))
                {
                    txtInCarNo.Text = carNo;
                    txtInResult.Text = "";
                }
                else if ("out".Equals(inOut))
                {
                    txtOutCarNo.Text = carNo;
                    txtOutResult.Text = "";
                }
            }
            else if ("Check".Equals(type))
            {
                bool result = (bool)jsonObj.GetValue("result");
                String inOut = (String)jsonObj.GetValue("inOut");
                String message = (String)jsonObj.GetValue("message");

                if (result)
                {
                    if ("in".Equals(inOut))
                    {
                        txtInResult.Foreground = Brushes.Green;
                        txtInResult.Text = "正常放行";
                    }
                    else if ("out".Equals(inOut))
                    {
                        txtOutResult.Foreground = Brushes.Green;
                        txtOutResult.Text = "正常放行";
                    }
                    LoadData();
                }
                else
                {
                    if ("in".Equals(inOut))
                    {
                        txtInResult.Foreground = Brushes.Red;
                        txtInResult.Text = message;
                        //MessageBox.Show(message);
                       
                    }
                    else if ("out".Equals(inOut))
                    {
                        txtOutResult.Foreground = Brushes.Red;
                        txtOutResult.Text = message;
                        //MessageBox.Show(message);


                    }
                }
            }
        }

        private void timeCycle(object sender, EventArgs e)
        {
            LoadData();
        }

        public void doDataRefresh(object sender, RoutedEventArgs e)
        {
            LoadData();
        }

        private void showPassWindowIn(object sender, RoutedEventArgs e)
        {

            Record record = (Record)DGInList.SelectedItem;

            PassWindow passWindow = new PassWindow();
            passWindow.setInOutType("in");
            passWindow.setCarNo(record.carNo);
            passWindow.Owner = mainWindow;

            bool result = (bool)passWindow.ShowDialog();
            if (result)
            {
                txtInCarNo.Text = record.carNo;
                txtInResult.Foreground = Brushes.Green;
                txtInResult.Text = "手动放行";
                LoadData();
            }
        }

        private void showPassWindowOut(object sender, RoutedEventArgs e)
        {


            Record record = (Record)DGOutList.SelectedItem;

            PassWindow passWindow = new PassWindow();
            passWindow.setInOutType("out");
            passWindow.setCarNo(record.carNo);
            passWindow.Owner = mainWindow;

            bool result = (bool)passWindow.ShowDialog();
            if (result)
            {
                txtOutCarNo.Text = record.carNo;
                txtOutResult.Foreground = Brushes.Green;
                txtOutResult.Text = "手动放行";
                LoadData();
            }
        }

        private void showCheckWindowIn(object sender, RoutedEventArgs e)
        {
            Record record = (Record)DGInList.SelectedItem;
            CheckWindow checkWindow = new CheckWindow();
            checkWindow.setBillNo(record.id);
            checkWindow.Owner = mainWindow;
            bool result = (bool)checkWindow.ShowDialog();
            if (result)
            {
                LoadData();
            }
        }

        private void DGOutList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }


    }
}
